package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.Depart;
import com.lhdx.practical.bean.StudentGroup;
import com.lhdx.practical.bean.Task;
import com.lhdx.practical.config.UploadConfig;
import com.lhdx.practical.service.DepartService;
import com.lhdx.practical.service.StudentGroupService;
import com.lhdx.practical.service.TaskService;
import com.lhdx.practical.utils.Constants;
import com.lhdx.practical.utils.DateUtils;
import com.lhdx.practical.utils.FileUtil;
import com.lhdx.practical.utils.JsonUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private UploadConfig uploadConfig;
    @Autowired
    private TaskService taskService;
    @Autowired
    private StudentGroupService groupService;
    @Autowired
    private DepartService departService;
    @Autowired
    private HttpServletRequest request;

    //处理文件上传
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public @ResponseBody
    String uploadImg(@RequestParam("file") MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        if (!file.isEmpty()) {
            String url = "";
            try {
                String fileName = file.getOriginalFilename();
                fileName = FileUtil.RenameToUUID(fileName);
                url = "/files/"+fileName;
                //System.out.println("==========图片大小："+file.getSize() + "   图片路径："+uploadConfig.getUploadPath());
                FileUtil.uploadFile(file.getBytes() , uploadConfig.getUploadPath()+"/files/", fileName);
            } catch (Exception e) {
                e.printStackTrace();
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"文件上传失败","");
            }
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"上传成功",url);
        } else {
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"文件不存在","");
        }
        return jsonObject.toJSONString();
    }

    /**
     * 打包下载
     * @param response
     * @param type   0个人作业 1小组作业
     * @param id
     */
    @CrossOrigin
    @GetMapping("/downloadZIP")
    @ResponseBody
    public void downloadZIP(HttpServletResponse response,int type,long id) {
        //生成打包下载后的zip文件名
        String papersZipName = "";
        //zip文件保存路径
        String zipPath = "";
        List<Task> tasks = null;
        if(type == 1){
            //单元作业打包
            StudentGroup group = groupService.findById(id);
            tasks = taskService.findAllByGroupidAndType(id,type);
            papersZipName = group.getGroupname() +"-小组作业.zip";
            zipPath = uploadConfig.getUploadPath() + "/" + papersZipName;
        }else if(type == 0){
            //个人年级作业打包
            Depart depart = departService.findById(id);
            tasks = taskService.findAllByGradeidAndType(id,type);
            papersZipName = depart.getDepartname() +".zip";
            zipPath = uploadConfig.getUploadPath() + "/" + papersZipName;
        }
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
            for(Task task : tasks){
                if(task.getAttachments() != null && task.getAttachments().length() > 0){
                    FileInputStream fis = new FileInputStream(uploadConfig.getUploadPath() + "/" + task.getAttachments());
                    //System.out.println(task.getAttachments());
                    String suffix = task.getAttachments().split("\\.")[1];
                    //System.out.println(suffix);
                    out.putNextEntry(new ZipEntry(task.getAuthorname()+"-"+ DateUtils.getLongToDateTime(task.getCreatetime()) +"."+suffix));
                    //写入压缩包
                    int len;
                    byte[] buffer = new byte[1024];
                    while ((len = fis.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.closeEntry();
                    fis.close();
                }
            }
            out.close();
            out.flush();
            FileUtil.downloadFile(request,response,papersZipName,zipPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
